import React, { memo, useEffect, useMemo, useState } from "react";
import { ActivityIndicator, Alert, Button, StatusBar, View } from "react-native";
import VideoPlayer from "react-native-media-console";
import Orientation from "react-native-orientation-locker";
import { styles } from "./style";

import { useAnimations } from "@react-native-media-console/reanimated";
import { isIos, VIDEO } from "../../helpers/constants";
import useBackbuttonHandler from "../../hooks/useBackButtonHandler";
import { noop } from "../../helpers/functional";
import { VideoScreenProps } from "../../types/NavigationTypes";
import { OnProgressData, OnVideoErrorData } from "react-native-video";
import { SafeAreaView } from "react-native-safe-area-context";

const videoRef = React.createRef<any>();

const VideoScreen: React.FC<VideoScreenProps> = ({ route, navigation }) => {
  const { data } = route.params?.data;

  const [loading, setLoading] = useState(true);

  const [fullScreenTapEnabled, setFullScreenTapEnabled] = useState(false);
  const [videoDisplayMode, setVideoDisplayMode] = useState<
    "portrait" | "landscape"
  >(VIDEO.videoDisplayModes.portrait);
  // Use this boolean to show / hide ui when pip mode changes

  const isPortrait = useMemo(() => {
    return videoDisplayMode === VIDEO.videoDisplayModes.portrait;
  }, [videoDisplayMode]);

  useEffect(() => {
    const delay = setTimeout(() => {
      setFullScreenTapEnabled(true);
    }, 0); //this is workaround for https://github.com/LunatiqueCoder/react-native-media-console/issues/76 issue.
    return () => {
      clearTimeout(delay);
    }; // Clear the timeout when the effect unmounts
  }, []);

  useEffect(() => {
    const delay = setTimeout(() => {
      videoDisplayMode === VIDEO.videoDisplayModes.portrait
        ? Orientation.lockToPortrait()
        : Orientation.lockToLandscape();
    }, 0);
    return () => {
      clearTimeout(delay);
    }; // Clear the timeout when the effect unmounts
  }, [videoDisplayMode]);

  const switchToPortrait = () => {
    setVideoDisplayMode(VIDEO.videoDisplayModes.portrait);
    if (!isIos()) {
      videoRef?.current?.dismissFullscreenPlayer();
    }
  };

  const switchToLandscape = () => {
    setVideoDisplayMode(VIDEO.videoDisplayModes.landscape);
    if (!isIos()) {
      videoRef?.current?.presentFullscreenPlayer();
    }
  };

  const onFullScreenIconToggle = () => {
    if (fullScreenTapEnabled) {
      if (isPortrait) {
        switchToLandscape();
      } else {
        switchToPortrait();
      }
    }
  };

  const _onBuffer = () => {
    setLoading(true);
  };

  const _onError = (error: OnVideoErrorData) => {
    console.error(error);
  };

  const _onLoad = () => {
    setLoading(false);
  };

  const _onProgress = (data: OnProgressData) => {
    //console.log(data);
  };

  useBackbuttonHandler(!isPortrait ? switchToPortrait : noop);

  return (
    
    <SafeAreaView style={{ flex: 1, backgroundColor: "black" }}>
     <StatusBar barStyle={"light-content"}/>
      <View
        style={
          isPortrait
            ? styles.portraitVideoContainer
            : styles.landscapeVideoContainer
        }
      >
        {loading && (
          <ActivityIndicator size="large" style={styles.loadingIndicator} />
        )}

        <VideoPlayer
          source={{ uri: data.playUrl }}
          showOnStart={false}
          title="Big Buck Bunny 2024"
          onEnterFullscreen={onFullScreenIconToggle}
          onExitFullscreen={onFullScreenIconToggle}
          onBack={switchToPortrait}
          videoRef={videoRef}
          disableFocus={true}
          disableBack={isPortrait}
          useAnimations={useAnimations}
          repeat={false}
          playInBackground={false}
          videoStyle={{ backgroundColor: "black" }}
          disableDisconnectError={true}
          onBuffer={_onBuffer}
          onError={_onError}
          onLoad={_onLoad}
          onProgress={_onProgress}
          seekColor="white"
          controlAnimationTiming={VIDEO.controlAnimationTiming}
          controlTimeoutDelay={VIDEO.controlTimeoutDelay}
          rewindTime={VIDEO.rewindTime}
          resizeMode={VIDEO.resizeMode}
          disableVolume={true}
          disableSeekButtons={true}
          disableSeekbar={false}
        />

        <Button
          title="返回"
          onPress={() => {
            if (isPortrait) {
              navigation.goBack();
            } else {
              switchToPortrait();
            }
          }}
        />
      </View>
    </SafeAreaView>
  );
};

export default VideoScreen;
